<template>
  <div ref="mainContent" class="main-content">
    <!-- 以表格的方式展示 -->
    <!-- 默认展示方式 -->
    <div v-if="!filePreview && mainData">
      <el-table v-if="isShowDetail" :data="mainData" border>
        <el-table-column
          prop="name"
          label="ITEMS"
        >
          <template slot-scope="scope">
            <div class="ali-d-flex">
              <span class="ali-font20 ali-pr8"><i class="fa fa-folder" aria-hidden="true" /></span>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="category"
          label="TYPE"
        >
          <template slot-scope="scope">
            <div class="ali-d-flex">
              <div style="height: 3em">
                <img class="ali-h100" alt="" :src="getBgUrl(scope.row)">
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="TIME"
        >
          <template slot-scope="scope">
            <div class="ali-d-flex">
              <span>{{ new Date(scope.row.created_at).toLocaleDateString() }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="size"
          label="SIZE"
        >
          <template slot-scope="scope">
            <div class="ali-d-flex">
              <span>{{ scope.row.size || '未知' }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <ul v-else class="file-list">
        <el-tooltip v-for="(item,i) in mainData" :key="i" class="item" effect="dark" :content="item.name" placement="right">
          <li :class="{'ali-bg-cover':isBgCover(item)}" :style="{'background':`rgb(91, 104, 112) url(${getBgUrl(item)}) no-repeat center`}" class="file-list-item " @click="getFileDetail(item.file_id,item.drive_id,item)">
            <div class="name-wrap">
              <span class="name">{{ item.name }}</span>
              <img v-if="!['others'].includes(item.category)" v-lazy="item.url" :src="item.url" class="ali-d-none" alt="">
              <img v-lazy="item.thumbnail" :src="item.thumbnail" class="ali-d-none" alt="">
            </div>
          </li>
        </el-tooltip>
      </ul>
    </div>
    <div v-else-if="fileNeedPassword" class="pass-wrap">
      <el-input v-model="fileNeedPassword.password" class="ali-mr10" type="password" placeholder="请输入密码" /><el-button @click="getFileDetailByPass">确定</el-button>
    </div>
    <div v-else-if="filePreview">
      <div class="ali-d-flex preview-head">
        <h3 class="file-name">{{ filePreview.name }}</h3>
        <div class="btn">
          <el-dropdown>
            <el-button type="primary" size="small">
              更多菜单<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>分享</el-dropdown-item>
              <el-dropdown-item id="thunder">迅雷</el-dropdown-item>
              <el-dropdown-item :loading="downLoading" @click.native="handleDown">下载</el-dropdown-item>
              <el-dropdown-item v-if="isVideo" :loading="downLoading" @click.native="handlePotPlayer">PotPlayer</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div v-show="isVideo" ref="dpContainer" class="video-wrap" />
      <div v-if="isImage" class="img-wrap">
        <img :src="filePreview.url" alt="">
      </div>
      <div v-if="isAudio" class="audio-wrap">
        <audio preload="auto" controls="" :src="filePreview.url" style="outline: none; width: 100%;" />
      </div>
      <div v-if="filePreview.category === 'others'" class="others-wrap markdown-body">
        <pre id="res"><code v-html="filePreview.afterRenderResult" /></pre>
        <el-button class="copy-btn" type="button" size="small" @click="handleCopy({key:filePreview.afterRenderResult})">复制</el-button>
      </div>
      <div v-if="[5,6,'zip'].includes(filePreview.category)" class="audio-wrap ali-align-center">
        该文件不支持预览
      </div>
    </div>
    <slot />
    <!--    <div class="footer">木之下-云盘v1.0.0</div>-->

    <a ref="top" href="javascript:" class="cd-top  cd-fade-out" @click="backPageTop" />
  </div>
</template>
<script>
import { getAliPanData, getFileDetail, handleFileDownloadLogic } from '@/api/aliPan'
import DPlayer from 'dplayer'
import Clipboard from 'clipboard'
import { downloadByLink, LEFT_FILE_LIST } from '@/views/ali-pan/config'
import { NETWORK_DISK_TYPE } from '@/utils/enum'

import hljs from 'highlight.js'
import 'highlight.js/styles/panda-syntax-dark.css'
// 所有的主题：https://highlightjs.org/examples
export default {
  name: 'AliMainContent',
  props: {
    mainData: {
      type: [Array, Object],
      default() {
        return []
      }
    },
    fullFileIdArr: {
      type: Array,
      default() {
        return []
      }
    },
    fileNeedPassword: {
      type: [Array, Object],
      default() {
        return []
      }
    }
  },
  data() {
    return {
      dp: null,
      url: 'https://pan.rawchen.com/static/img/folder.jpg',
      filePreview: null,
      isShowDetail: false,
      timer: null,
      downLoading: false
    }
  },
  computed: {
    isVideo() {
      return [1, 'video'].includes(this.filePreview.category)
    },
    isImage() {
      return [3, 'image'].includes(this.filePreview.category)
    },
    isAudio() {
      return [2, 'audio'].includes(this.filePreview.category)
    }
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer)
  },
  mounted() {
    this.$refs.mainContent.onscroll = this.handleScroll

    this.$nextTick(() => {

    })
  },
  methods: {
    handleDown() {
      if (LEFT_FILE_LIST[this.filePreview.root] && LEFT_FILE_LIST[this.filePreview.root].handleFileDownloadLogic) {
        return LEFT_FILE_LIST[this.filePreview.root].handleFileDownloadLogic(this.filePreview, this)
      }
    },
    handlePotPlayer() {
      if (LEFT_FILE_LIST[this.filePreview.root] && LEFT_FILE_LIST[this.filePreview.root].handlePotPlayer) {
        return LEFT_FILE_LIST[this.filePreview.root].handlePotPlayer(this.filePreview, this)
      }
    },
    isBgCover(item) {
      if (item.category === 6 && item.isdir === 0) return false
      return !['audio', 'others', 2, 'zip'].includes(item.category)
    },
    handleCopy(record, e) {
      this.$copyText(record.key).then(() => {
        this.$message.success('复制成功')
      })
    },
    handleScroll() {
      const scrollTop = this.$refs.mainContent.scrollTop || this.$refs.mainContent.pageYOffset || this.$refs.mainContent.scrollTop
      if (!this.$refs.top) { return }
      if (scrollTop > 100) {
        this.$refs.top.classList.add('cd-is-visible')
      } else {
        this.$refs.top.classList.remove('cd-is-visible')
      }
    },
    backPageTop() {
      this.$refs.mainContent.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
    // 获取文件的封面
    getBgUrl(item) {
      if (LEFT_FILE_LIST[item.root] && LEFT_FILE_LIST[item.root].getMediaCover) {
        return LEFT_FILE_LIST[item.root].getMediaCover(item)
      }
      const mediaList = {
        audio: 'https://pan.rawchen.com/static/img/type/music.png',
        video: item.thumbnail,
        others: 'https://pan.rawchen.com/static/img/type/code.png',
        dir: 'https://pan.rawchen.com/static/img/folder.jpg',
        zip: 'https://pan.rawchen.com/static/img/type/compress.png'
      }
      if (item.url && !mediaList[item.category]) return item.url
      return mediaList[item.category] || this.url
    },
    initDPlayer() {
      if (!this.isVideo) {
        // this.$refs.dpContainer.style.display = "none"
        return
      }
      const options = {
        container: this.$refs.dpContainer,
        video: {
          url: this.filePreview.url
        },
        volume: 0.5,
        screenshot: true

      }
      this.dp = new DPlayer(options)
    },
    getFileDetail(file_id, drive_id, item) {
      // this.$emit('update:fullFileIdArr', this.fullFileIdArr.concat({ file_id, drive_id }))
      if (LEFT_FILE_LIST[item.root] && LEFT_FILE_LIST[item.root].getFileDetail) {
        return LEFT_FILE_LIST[item.root].getFileDetail(item, this, LEFT_FILE_LIST[item.root])
      }
    },
    getFileDetailByPass() {
      this.getFileDetail(this.fileNeedPassword.file_id, this.fileNeedPassword.drive_id, this.fileNeedPassword)
    },
    getStyle(item) {
      const url = item.url || this.url
      return `rgb(91, 104, 112) url(${url}) no-repeat center`
    },
    async getFileItemDetail(params) {
      const loading = this.$loading({})
      await getFileDetail(params).then((res) => {
        if (res.code === 0 && res.data) {
          this.filePreview = res.data
          // 视频
          this.$nextTick(() => {
            this.initDPlayer()
          })
        }
      }).finally(() => {
      })
      // 代码
      if (this.filePreview.category === 'others') {
        await this.getBinaryData(this.filePreview.url)
      }

      loading.close()
    },
    resetFile() {
      this.filePreview = null
      this.$emit('update:mainData', null)
      this.$emit('update:fileNeedPassword', null)
    },
    async getBinaryData(url) {
      // 使用 Fetch API 获取链接内容
      await fetch(url)
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok')
          }
          return response.text()
        })
        .then(textData => {
          // 在这里进行代码的高亮
          const file_extension = this.filePreview.file_extension
          // if (['conf'].includes(this.filePreview.file_extension)) {
          //   file_extension = 'bash'
          // }
          let preCode = ''
          try {
            preCode = hljs.highlight(file_extension, textData, true).value
          } catch (err) {
            preCode = hljs.highlight('bash', textData, true).value
          }

          // console.log(preCode)
          // 在这里你可以使用文本数据
          this.$set(this.filePreview, 'afterRenderResult', preCode)
          // 这里可以进行进一步的文本处理
        })
        .catch(error => console.error('Error fetching data:', error))
    }
  }
}
// http://127.0.0.1:9360/pan-api/auth/refresh_token
</script>

<style  lang="scss" scoped>
.video-wrap{
  ::v-deep{
    .dplayer-controller-mask{
      display: none;
    }
  }
}
.markdown-body{
  position: relative;
  .copy-btn{
    position: absolute;
    top:1em;
    right:2em;
  }
}
.markdown-body pre{
  margin-top: 0;
  color: #e6e6e6;
  background: #2a2c2d;
  border-radius: 3px;
  font-size: 16px;
  line-height: 1.45;
  overflow: auto;
  padding: 16px;

}

::v-deep{
  .el-table__row td{
    padding:0;
  }
  .el-table{
    color:#333;
    td{
      border-bottom: solid rgb(218, 215, 215) 1px;
    }
  }
  .el-table--border::after, .el-table--group::after, .el-table::before{
    background: none;
  }
}
.img-wrap{
  margin:0 1em .2em 1em;
  max-width: 100%;
  border: 4px dotted rgb(148, 180, 209);
  padding: 6px;
  text-align: center;
  img{
    max-width: 100%;
  }
}
.audio-wrap{
  margin:0 1em .2em 1em;
}
.ali-align-center{
  text-align: center;
  font-size: .8em;
}
.preview-head{
  justify-content: space-between;
  padding-right: 1em;
  .btn{
    margin: 1em 0 1em 0.2em;
    display: flex;
  }
}
.file-name{
  max-width: 66%;
  text-overflow: ellipsis;
  margin: 1.2em 0.2em;
  padding-left: 1em;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
}
ul.file-list, .file-list li{padding:0;margin: 0;list-style: none}
  .main-content{
    position: absolute;
    width: 80%;
    height: 100%;
    margin-left: 20%;
    overflow: scroll;

    .footer{
      position: absolute;
      bottom:10px;
      left:50%;font-size: 12px;
      color:#444;
      transform: translateX(-50%);
    }
    &::-webkit-scrollbar{
      width: 10px;
      height: 0;
    }
    &::-webkit-scrollbar-thumb{
      background-color: #bbb;
    }
    &::-webkit-scrollbar-track{
      background-color: #f1f1f1;
    }
  }
  .file-list{
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    padding-top: 8px;
    padding-left: 5px;
    padding-right: 5px;

    .file-list-item{
      cursor: pointer;
      font-size: .8em;
      height: 8em;
      margin: 4px;
      padding: unset;
      border-radius: 5px;
      box-shadow: 0 0 7px #dfdfdf;
      background: rgb(91, 104, 112) url("https://pan.rawchen.com/static/img/folder.jpg") no-repeat center;
      background-size: cover;
      transition: all 0.2s;
      &:hover{
        background-color: #7e98a8 !important;
        transform: scale(1.03);
      }
      .name-wrap{
        color: white;
        text-align: center;
        background: linear-gradient(90deg, #0000008f, #00000047);
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-top: 84px;
        height: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .name{
        width: 100%;
        padding-left: 0.3em;
        padding-right: 0.3em;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

      }
    }
  }
  .ali-d-none{
    display: none;
  }
  .video-wrap, .others-wrap{
    padding:0 1em .2em 1em;
  }
  .ali-bg-cover{
    background-size: cover !important;
  }

.cd-top {
  z-index: 9999;
  display: inline-block;
  height: 40px;
  width: 40px;
  position: fixed;
  bottom: 60px;
  right: 2em;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  text-indent: 100%;
  white-space: nowrap;
  background: rgba(232, 98, 86, 0.8) url("../../../assets/img/page/cd-top-arrow.svg") no-repeat center 50%;
  visibility: hidden;
  opacity: 0;
  transition: all 0.3s;
}

.cd-top.cd-fade-out:hover {
  opacity: 1;
}

.cd-top.cd-is-visible {
  visibility: visible;
  opacity: 1;
}
.pass-wrap{
  padding:10px;
  display: flex;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.demonstration {
  display: block;
  color: #8492a6;
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
